class PostsController < ApplicationController
  
  before_filter :login_required, :only => [:new, :edit, :create, :update, :destroy]
  before_filter :set_current_menu_and_title
  
  def index
    @posts = Post.find(:all)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }
    end
  end

  def show
    @post = Post.find(params[:id])
    @post.views_count = @post.views_count + 1
    @post.save
    @comments = Comment.paginate_by_post_id(@post.id, :per_page => 10, :page => params[:page], :order => 'created_at asc')
    @title = @post.title
    @keywords = @post.tag_list.join(' ')
    @description = @post.content[0,100]
  end

  # GET /posts/new
  # GET /posts/new.xml
  def new
    @post = Post.new
    @forum = Forum.find(params[:forum_id])

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @post }
    end
  end

  # GET /posts/1/edit
  def edit
    @post = Post.find(params[:id])
  end

  # POST /posts
  # POST /posts.xml
  def create
    @post = Post.new(params[:post])
    @post.user_id = current_user.id

    respond_to do |format|
      if @post.save
        flash[:notice] = 'Post was successfully created.'
        format.html { redirect_to(@post) }
        format.xml  { render :xml => @post, :status => :created, :location => @post }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /posts/1
  # PUT /posts/1.xml
  def update
    @post = Post.find(params[:id])

    respond_to do |format|
      if @post.update_attributes(params[:post])
        flash[:notice] = 'Post was successfully updated.'
        format.html { redirect_to(@post) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.xml
  def destroy
    @post = Post.find(params[:id])
    @post.destroy

    respond_to do |format|
      format.html { redirect_to(posts_url) }
      format.xml  { head :ok }
    end
  end

  private
    def set_current_menu_and_title
      @current_menu = :forum
      @title = "论坛"
    end
end
